import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

class MyStack{
    int[] elem;//使用数组来模拟栈
    int usedSize;//栈中有多少元素
    private static final int INIT = 10;//默认初始化10个
    public MyStack(){
        elem = new int[INIT];
    }
    //进栈
    public int push(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem, elem.length*2);
        }
        elem[usedSize] = val;
        usedSize++;
        return elem[usedSize];
    }
    //出栈
    public int pop(){
        if(empty()){
            System.out.println("栈中没有元素！");
            return -1;
        }
        usedSize--;
        return elem[usedSize];
    }
    //得到栈顶元素，但不要出栈
    public int peek(){
        if(empty()){
            System.out.println("栈中没有元素！");
            return -1;
        }
        return elem[usedSize-1];
    }
    //栈有多少元素-栈的大小
    public int size(){
        return usedSize;
    }
    //栈是否为空
    public boolean empty(){
        return 0 == usedSize;
    }
    //栈是否满了
    public boolean isFull(){
        return elem.length == usedSize;
    }
}
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ans = new LinkedList();
        if(nums == null || nums.length < 4) return ans;
        Arrays.sort(nums);
        int len = nums.length;
        for(int i=0; i<len-3; i++){
            if(i>0 && nums[i-1] == nums[i]) continue;
            if((long)nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target){
                break;
            }
            if((long)nums[i]+nums[len-1]+nums[len-2]+nums[len-3]<target){
                continue;
            }
            for(int j=i+1; j<len-2; j++){
                if(j > i+1 && nums[j] == nums[j-1]) continue;
                if((long)nums[i]+nums[j]+nums[j+1]+nums[j+2]>target){
                    break;
                }
                if((long)nums[i]+nums[j]+nums[len-1]+nums[len-2]<target){
                    continue;
                }
                int left = j+1;
                int right = len-1;
                while(left < right){
                    long sum = (long)nums[i] + nums[j] + nums[left] + nums[right];
                    if(sum == target){
                        ans.add(List.of(nums[i],nums[j],nums[left],nums[right]));
                        left++;
                        while(left<right&&nums[left]==nums[left-1]){
                            left++;
                        }
                        right--;
                        while(left < right && nums[right] == nums[right+1]){
                            right--;
                        }
                    }else if(sum < target){
                        left++;
                    }else{
                        right--;
                    }
                }
            }
        }
        return ans;
    }
}
